package com.huangyi;

public class Main {
    public static void main(String[] args) {
        //删除字符串中的所有相邻重复项
        class Solution {
            public String removeDuplicates(String s) {
                StringBuffer stk = new StringBuffer();
                for (int i = 0; i < s.length(); i++) {
                    char ch = s.charAt(i);
                    // 栈非空且栈顶等于当前字符 -> 抵消（弹出）
                    if (stk.length() > 0 && stk.charAt(stk.length() - 1) == ch) {
                        stk.deleteCharAt(stk.length() - 1);
                    } else {
                        // 否则入栈
                        stk.append(ch);
                    }
                }
                return stk.toString();
            }
        }


        //比较含退格的字符串
        class Solution2 {
            public boolean backspaceCompare(String s, String t) {
                StringBuffer a = new StringBuffer();
                StringBuffer b = new StringBuffer();

                // 处理 s
                for (int i = 0; i < s.length(); i++) {
                    char ch = s.charAt(i);
                    if (ch == '#') {
                        if (a.length() > 0) a.deleteCharAt(a.length() - 1); // 退格 -> 弹出
                    } else {
                        a.append(ch); // 字母 -> 入栈
                    }
                }

                // 处理 t
                for (int j = 0; j < t.length(); j++) {
                    char ch = t.charAt(j);
                    if (ch == '#') {
                        if (b.length() > 0) b.deleteCharAt(b.length() - 1);
                    } else {
                        b.append(ch);
                    }
                }

                // 比较最终文本
                return a.toString().equals(b.toString());
            }
        }

    }
}